package com.cskaoyan.bean;

import com.cskaoyan.util.ProxyUtil;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.InvocationHandler;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@Component
public class CustomBeanPostProcessor implements BeanPostProcessor {
    @Override
    public Object postProcessBeforeInitialization(Object bean, String beanName) throws BeansException {
        //System.out.println("hello");

        //动态代理：用什么动态代理？
        Class<?>[] interfaces = bean.getClass().getInterfaces();
        if (interfaces != null && interfaces.length > 0) {
            Object proxy = Proxy.newProxyInstance(bean.getClass().getClassLoader(),bean.getClass().getInterfaces(), new java.lang.reflect.InvocationHandler() {
                @Override
                public Object invoke(Object proxy, Method method, Object[] objects) throws Throwable {
                    if (bean instanceof Animal && "shout".equals(method.getName())) {
                        System.out.println("hello");
                        Object invoke = method.invoke(bean, objects);
                        System.out.println("world");
                        return invoke;
                    }
                    /*if (bean instanceof Animal *//*&& method.getName().equals("shout")*//*) {

                    }*/
                    Object invoke = method.invoke(bean, objects);
                    return invoke;
                }
            });
            return proxy;
        }

        Object proxy = Enhancer.create(bean.getClass(), new InvocationHandler() {
            @Override
            public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
                System.out.println("hello");
                Object invoke = method.invoke(bean, objects);
                System.out.println("world");
                return invoke;
            }
        });
        //Object proxy = ProxyUtil.getServiceProxy(bean.getClass());
        return proxy;
    }

    @Override
    public Object postProcessAfterInitialization(Object bean, String beanName) throws BeansException {
        //System.out.println("world");
        return null;
    }
}
